package com.newtouch.krd_app.view;

import static com.newtouch.krd_app.util.ConstUtil.WidgetViewImageTime;
import static com.newtouch.krd_app.util.ConstUtil.WidgetViewWebPeriodTime;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.android.ijk.player.IJK;
import com.android.ijk.player.listener.OnIJKVideoListener;
import com.android.ijk.player.view.IJKVideoView;
import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.newtouch.krd_app.MainActivity;
import com.newtouch.krd_app.R;
import com.newtouch.krd_app.http.api.TerminalApi;
import com.newtouch.krd_app.util.BaseUrlUtil;
import com.newtouch.krd_app.util.ControllerInterface;
import com.newtouch.krd_app.util.DeviceUtil;
import com.newtouch.krd_app.util.SPUtils;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * author : TQ
 * time   : 2023/2/14
 * desc   :
 */
public class WidgetViewijkVideo extends WidgetView  {
    private static final String TAG = "WidgetBoxVideo";
    private IJKVideoView ijk;

    /**
     * 构造函数
     *
     * @param context
     */
    public WidgetViewijkVideo(Context context) {
        super(context);
    }

    public WidgetViewijkVideo(Context context, ControllerInterface controllerInterface) {
        super(context, controllerInterface);
    }
//    private SurfaceHolder.Callback callback = ;

    @Override
    public View initView() {
        view = View.inflate(context, R.layout.widget_player_view, null);
        //初始化建议配置在Application
        IJK.config().initOptions();
        ijk = view.findViewById(R.id.ijk);
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) ijk.getLayoutParams();
        if (DeviceUtil.getScreenHeight((Activity) context)>DeviceUtil.getScreenWidth((Activity) context)){
            layoutParams.height = (int) (0.34375* DeviceUtil.getScreenHeight((Activity) context));
        }else {
            layoutParams.height = (int) DeviceUtil.getScreenWidth((Activity) context);
        }
        //直播设置，会控制进度条是否可拖动。
        ijk.setLiveSource(false);
        ijk.getMediaPlayer().setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", 1);
//        ijk.getControlViewHolder().getControlView().setVisibility(View.GONE);
        ijk.setOnIJKVideoListener(new OnIJKVideoListener() {
            @Override
            public void onVideoPrepared(IMediaPlayer player) {

            }

            @Override
            public void onVideoSizeChanged(IMediaPlayer player, int width, int height, int sarNum, int sarDen) {

            }

            @Override
            public void onVideoSeekEnable(boolean enable) {

            }

            @Override
            public void onVideoBufferingStart(IMediaPlayer player, int args) {
                Log.e(TAG, "onVideoBufferingStart: "+args);
            }

            @Override
            public void onVideoBufferingEnd(IMediaPlayer player, int args) {
                Log.e(TAG, "onVideoBufferingEnd: "+args);
            }

            @Override
            public void onVideoRenderingStart(IMediaPlayer player, int args) {
                Log.e(TAG, "onVideoRenderingStart: "+args);
            }

            @Override
            public void onVideoRotationChanged(IMediaPlayer player, int args) {
                Log.e(TAG, "onVideoRotationChanged: "+args);
            }

            @Override
            public void onVideoTrackLagging(IMediaPlayer player, int args) {
                Log.e(TAG, "onVideoTrackLagging: "+args);
            }

            @Override
            public void onVideoBadInterleaving(IMediaPlayer player, int args) {
                Log.e(TAG, "onVideoBadInterleaving: "+args);
            }

            @Override
            public void onVideoSeekComplete(IMediaPlayer player) {
                Log.e(TAG, "onVideoSeekComplete: ");
            }

            @Override
            public void onVideoProgress(IMediaPlayer player, long duration, long current) {
                Log.e(TAG, "onVideoBadInterleaving: "+current);
            }

            @Override
            public void onVideoCompletion(IMediaPlayer player) {
                Log.e(TAG, "onVideoCompletion: ");
                if (BaseUrlUtil.getInstance().isConnect){
                    controllerInterface.playEnd();
                }else{
                    if (timer == null) {
                        timer = new Timer();
                        timerTask = new TimerTask() {
                            @Override
                            public void run() {
                                controllerInterface.playEnd();
                            }
                        };
                    }
                    timer.schedule(timerTask,WidgetViewWebPeriodTime);
                }

            }

            @Override
            public void onVideoError(IMediaPlayer player, int framework_err, int impl_err) {
                Log.e("onVideoError",""+framework_err+"  --- "+impl_err);
                ToastUtils.show("播放失败,播放下一个");
            }
        });

        return view;
    }


    @Override
    public void setFilesDTO(TerminalApi.Bean.FilesDTO filesDTO) {
        super.setFilesDTO(filesDTO);
        if (ijk != null){
            String json = (String) SPUtils.get(context,"CarcheFiles","");
            //播放视频
            if (!TextUtils.isEmpty(json)){
                HashMap hashMap = new Gson().fromJson(json,HashMap.class);
                String url = (String) hashMap.get(filesDTO.getFileId());
                if (!TextUtils.isEmpty(url)){
                    ijk.setDataSource(url);
                }else {
                    ijk.setDataSource(filesDTO.getFilePath());
                }
            }else {
                ijk.setDataSource(filesDTO.getFilePath());
            }

        }else {
            ToastUtils.show("ijk为空，播放失败，播放下一个");
            controllerInterface.playEnd();
        }

    }

    /**
     * 直接开始播放（资源已经准备好）
     */
    @Override
    public void startPlay() {
        ijk.start();

    }


    @Override
    public void terminatePlay() {
        super.terminatePlay();
        try {
            ijk.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getDuration() {
        if (ijk!=null && ijk.getMediaPlayer()!=null){
            return (int) ijk.getMediaPlayer().getDuration();
        }else {
            return super.getDuration();
        }
    }
}